//
//  JMFrequencyViewController.m
//  OpenSesame
//
//  Created by zhangjiaming on 15/12/21.
//  Copyright © 2015年 OpenSesame. All rights reserved.
//

#import "JMFrequencyViewController.h"
#import "JMPeripheralView.h"
#import "MBProgressHUD+JM.h"
#import "JMCenterManager.h"
#import "JMPeripheralCell.h"

@interface JMFrequencyViewController () <JMPeripheralViewDelegate, UITableViewDelegate, UITableViewDataSource, JMCenterManagerDelegate>
@property (weak, nonatomic) IBOutlet UILabel *topLabel; // 顶上的label
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *topLabelBottomConstraint; // 顶上label的底端约束

@property (weak, nonatomic) IBOutlet UIButton *nextBtn; // 下一步按钮
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *nextBtnBottomConstraint; // 下一步按钮的顶端约束
@property (weak, nonatomic) UIButton *bluetoothBtn;
@property (strong, nonatomic) UIView *shieldView; // 蒙版
@property (strong, nonatomic) JMPeripheralView *peripheralView;
@property (strong, nonatomic) JMCenterManager *mgrs;
@property (strong, nonatomic) NSMutableArray *peripherals; // 存放扫描到得外设对象

@property (weak, nonatomic) UIImageView *connectView; // 正在连接view
@property (strong, nonatomic) CBPeripheral *peripheral; // 连接的外设
@end

@implementation JMFrequencyViewController

- (NSMutableArray *)peripherals {
    if (!_peripherals) {
        _peripherals = [NSMutableArray array];
    }
    return _peripherals;
}

- (UIView *)shieldView {
    if (!_shieldView) {
        _shieldView = [[UIView alloc] init];
        _shieldView.frame = CGRectMake(0, 0, JMPhoneWidth, JMPhoneHeight);
        _shieldView.backgroundColor = [UIColor blackColor];
        _shieldView.alpha = 0.7;
    }
    return _shieldView;
}

- (JMPeripheralView *)peripheralView {
    if (!_peripheralView) {
        _peripheralView = [[JMPeripheralView alloc] initWithFrame:CGRectMake(30, JMPhoneHeight * 0.25, JMPhoneWidth - 60, JMPhoneHeight * 0.5)];
        _peripheralView.tableView.delegate = self;
        _peripheralView.tableView.dataSource = self;
        _peripheralView.delegate = self;
    }
    return _peripheralView;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    JMCenterManager *mgs = [JMCenterManager sharedCenterManager];
    if (mgs.connected) {
        self.bluetoothBtn.selected = YES;
    } else {
        self.bluetoothBtn.selected = NO;
    }
    self.mgrs = mgs;
    mgs.delegate = self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = JMColor(154, 208, 237);
    
    // 设置导航栏右侧内容
    UIButton* btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.frame = CGRectMake(0, 0, 60, 44);
    [btn setImage:[UIImage imageNamed:@"蓝牙 未连"] forState:UIControlStateNormal];
    [btn setImage:[UIImage imageNamed:@"蓝牙 按下"] forState:UIControlStateHighlighted];
    [btn setImage:[UIImage imageNamed:@"蓝牙"] forState:UIControlStateSelected];
    [btn addTarget:self action:@selector(scanBlueTooth) forControlEvents:UIControlEventTouchUpInside];
    btn.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, -25);
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:btn];
    self.bluetoothBtn = btn;
    
    // 设置顶端的topLabel
    self.topLabel.textColor = JMColor(49, 117, 153);
    if (JMPhoneWidth == 320) {
        // 4S需要缩小与下面控件的约束
        self.topLabelBottomConstraint.constant = 10.0;
    }
    
    // 设置下一步按钮
    [self.nextBtn setTitleColor:JMColor(49, 117, 153) forState:UIControlStateNormal];
    [self.nextBtn setBackgroundColor:JMColor(154, 208, 237)];
    if (JMPhoneWidth == 320) {
        // 4S需要缩小与上面控件的约束
        self.nextBtnBottomConstraint.constant = 10;
    }
    self.nextBtn.layer.borderColor = JMColor(49, 117, 153).CGColor;
    self.nextBtn.layer.borderWidth = 1.0;
    self.nextBtn.layer.cornerRadius = 10;
    self.nextBtn.layer.masksToBounds = YES;
}

/**
 *  扫描外设
 */
- (void)scanBlueTooth {
    // 添加蒙版
    [self.view addSubview:self.shieldView];

    // 添加展示外围设备的View
    [self.view addSubview:self.peripheralView];

    // 取出上次记住的外设名称
    NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
    NSString *peripheralName = [userDefault objectForKey:@"peripheralName"];
    if (peripheralName) {
        self.peripheralView.lastConncetLabel.text = peripheralName;
    }
    
    // 扫描
    JMCenterManager *mgs = [JMCenterManager sharedCenterManager];
    mgs.delegate = self;
    self.mgrs = mgs;
    [mgs beginScan];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - UITableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.peripherals.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    JMPeripheralCell *cell = [JMPeripheralCell cellWithTableView:tableView];
    CBPeripheral *peripheral = self.peripherals[indexPath.row];
    cell.peripheralLabel.text = peripheral.name;
    cell.height = 20;
    return cell;
}

/**
 *  选择需要连接的设备
 */
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    CBPeripheral *peripheral = self.peripherals[indexPath.row];
    // 向JMPeripheralView发送通知传送用户选择的外设名
    NSNotificationCenter *notification = [NSNotificationCenter defaultCenter];
    [notification postNotificationName:@"obtainPeripheralName" object:self.peripheralView userInfo:@{@"periphralName":peripheral.name}];
    
    // 保存需要记住的外设名称
    if (self.peripheralView.rememberBtn.selected) {
        NSUserDefaults *usersDefault = [NSUserDefaults standardUserDefaults];
        [usersDefault setValue:peripheral.name forKey:@"peripheralName"];
    }
}
#pragma mark - JMCenterManagerDelegate
// 扫描到新外设
- (void)centerManager:(JMCenterManager *)centerManager didScanNewPeripheral:(CBPeripheral *)peripheral WithAdvertisementData:(NSDictionary<NSString *,id> *)advertisementData RSSI:(NSNumber *)RSSI {
    // 添加外围设备
    if (![self.peripherals containsObject:peripheral] && peripheral.name != NULL) {
        [self.peripherals addObject:peripheral];
        
        // 刷新扫描的蓝牙
        [self.peripheralView.tableView reloadData];
    }
}

// 连接成功
- (void)centerManager:(JMCenterManager *)centerManager didconnectPeripheral:(CBPeripheral *)peripheral {
    // 改变蓝牙按钮的状态
    self.bluetoothBtn.selected = YES;
    [centerManager.manger stopScan];
    // 消除connectView
    [self.connectView removeFromSuperview];
}

// 失去连接
- (void)centerManager:(JMCenterManager *)centerManager didDisconnectPeripheral:(CBPeripheral *)peripheral {
    // 改变蓝牙按钮的状态
    self.bluetoothBtn.selected = NO;
}

#pragma mark - JMPeripheralViewDelegate
/**
 *  连接用户选择的外设
 */
- (void)peripheralView:(JMPeripheralView *)peripheralView didClickedConfirmBtn:(UIButton *)confirmBtn {
    // 删除peripheralView
    [self.peripheralView removeFromSuperview];
    [self.shieldView removeFromSuperview];
    for (CBPeripheral *peripheral in self.peripherals) {
        if ([peripheral.name isEqualToString:confirmBtn.titleLabel.text]) {
            [self.mgrs connectPeripheral:peripheral];
            self.peripheral = peripheral;
            
            // 显示正在连接
            NSMutableArray *array = [[NSMutableArray alloc] initWithObjects:[UIImage imageNamed:@"loadingpic1"],[UIImage imageNamed:@"loadingpic2"],[UIImage imageNamed:@"loadingpic3"],[UIImage imageNamed:@"loadingpic4"],[UIImage imageNamed:@"loadingpic5"], [UIImage imageNamed:@"loadingpic6"],[UIImage imageNamed:@"loadingpic7"],[UIImage imageNamed:@"loadingpic8"],nil ];
            UIImageView *imageView = [[UIImageView alloc] init];
            [self.view addSubview:imageView];
            imageView.width = 250;
            imageView.height = 45;
            imageView.center = self.view.center;
            imageView.animationImages = array;
            imageView.animationDuration = 4;
            [imageView startAnimating];
            self.connectView = imageView;
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self.connectView removeFromSuperview];
                [JMCenterManager stopScan];
                if (!self.mgrs.isConnected) {
                    [MBProgressHUD showError:@"连接超时"];
                    [self.mgrs cancelConnect:self.peripheral];
                }

            });
        }
    }
}

- (void)removeShieldView:(JMPeripheralView *)peripheralView {
    [self.peripheralView removeFromSuperview];
    [self.shieldView removeFromSuperview];
    if (self.mgrs.connected) {
        [JMCenterManager stopScan];
    }
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self.peripheralView removeFromSuperview];
    [self.shieldView removeFromSuperview];
    [self.connectView removeFromSuperview];
}
@end
